package Servlet;

import Bean.DgutBean;
import Bean.CheckBean;
import StudentDTO.UserCheckDTO;
import StudentDTO.UserInfoDTO;
import httpclient.MyPost;
import loginRegister.LoginBean;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 黄忠
 * 创建于2019-04-09
 */
@WebServlet(urlPatterns = {"/login/dgut"})
public class DgutServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws IOException {

        // 告诉浏览器，响应数据的数据格式与字符编码。否则会乱码。
        response.setContentType("text/html;charset=UTF-8");
        Jsonb jsonb = JsonbBuilder.create();

        //信息核对
        String token=request.getParameter("token");
        List<NameValuePair> formparams = new ArrayList<>();
        formparams.add(new BasicNameValuePair("token", token));
        formparams.add(new BasicNameValuePair("appid", "javaee"));
        formparams.add(new BasicNameValuePair("appsecret", "b3b52e43ccfd"));
        formparams.add(new BasicNameValuePair("userip", "10.0.2.2"));
        String checkStr= MyPost.post("https://cas.dgut.edu.cn/ssoapi/v2/checkToken",formparams);
        UserCheckDTO ucd=jsonb.fromJson(checkStr, UserCheckDTO.class);
        if(ucd.getAccess_token()==null){
            System.out.println("核对失败！");
            response.sendRedirect("https://cas.dgut.edu.cn?appid=javaee");
        }
        else {
            System.out.println(jsonb.toJson(ucd));

            //获取用户信息
            formparams.clear();
            formparams.add(new BasicNameValuePair("access_token", ucd.getAccess_token()));
            formparams.add(new BasicNameValuePair("openid", ucd.getOpenid()));
            String inforStr = MyPost.post("https://cas.dgut.edu.cn/oauth/getUserInfo", formparams);
            UserInfoDTO uid = jsonb.fromJson(inforStr, UserInfoDTO.class);
            if (uid.getName() == null) {
                System.out.println("验证失败！");
                response.sendRedirect("https://cas.dgut.edu.cn?appid=javaee");
            }
            else {
                System.out.println(jsonb.toJson(uid));
                HttpSession session = request.getSession(true);
                LoginBean loginBean=(LoginBean) session.getAttribute("login");
                if(loginBean!=null){
                    DgutBean dgutBean = new DgutBean(loginBean.getUserName(),uid.getUsername(),uid.getName(),uid.getGroup(),uid.getFaculty_title());
                    if(!dgutBean.isBeBind()){
                        dgutBean.dgut_save();
                        dgutBean.bind();
                        CheckBean.alert("账号绑定成功！");
                        System.out.println(uid.getUsername()+"账号绑定成功！");
                        response.sendRedirect("http://localhost:8080/main/main.jsp");
                    }
                    else{
                        CheckBean.alert("该账号已被绑定！");
                        response.sendRedirect("http://localhost:8080/main/main.jsp");
                    }
                }
                else{
                    DgutBean dgutBean = new DgutBean(uid.getUsername(),uid.getName(),uid.getGroup(),uid.getFaculty_title());
                    if(dgutBean.dgut_login()){
                        LoginBean login=new LoginBean();
                        login.setUserName(dgutBean.getUsername());
                        login.setPassword(dgutBean.getPassword());
                        login.login();
                        session=request.getSession();//获取session对象
                        session.setAttribute("login", login);//把列表保存到session对象中，以便在别的页面中获取个人信息
                        response.sendRedirect("http://localhost:8080/main/main.jsp");
                    }
                    else {
                            CheckBean.alert("该账号未被绑定，无法登陆！");
                            response.sendRedirect("https://cas.dgut.edu.cn/logout?callback=http://localhost:8080/login.jsp");
                        }
                    }
                }
            }
        }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doGet(request,response);
    }
}